// WebSocketService.tsx
import { message } from 'antd';
import { BACKEND_WS_LOCAL, BACKEND_WS_PROD } from '@/constants';

type WebSocketMessageHandler = (data: string) => void;

const isDev = process.env.NODE_ENV === 'development';

class WebSocketService {
  private socket: WebSocket | null = null;
  private userId: number | null = null;

  constructor(userId: number) {
    this.userId = userId;
  }

  /**
   * 创建连接
   */
  connect(): void {
    if (!this.userId) {
      console.error('User ID is required to establish a WebSocket connection.');
      return;
    }

    if (this.socket) {
      return;
    }

    this.socket = new WebSocket(
      `${isDev ? BACKEND_WS_LOCAL : BACKEND_WS_PROD}?userId=${this.userId}`,
    );

    this.socket.onopen = () => {
      console.log('Connected to the server');
    };

    this.socket.onmessage = (event) => {
      const data = event.data;
      console.log('Received message:', data);
      message.success(data);
    };

    this.socket.onclose = () => {
      console.log('Disconnected from the server');
    };
  }

  disconnect(): void {
    if (this.socket) {
      this.socket.close();
      this.socket = null;
    }
  }

  sendMessage(message: string): void {
    if (this.socket && this.socket.readyState === WebSocket.OPEN) {
      this.socket.send(message);
    } else {
      console.error('WebSocket is not connected.');
    }
  }

  onMessage(handler: WebSocketMessageHandler): void {
    if (this.socket) {
      this.socket.onmessage = (event) => {
        handler(event.data);
      };
    }
  }
}

export default WebSocketService;
